import { Dimensions } from 'react-native';
import { useNavigation } from '@react-navigation/native';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');
import { SafeAreaView } from 'react-native-safe-area-context';
// 按设计稿比例计算（假设设计稿宽度为 375）
const responsiveWidth = (value: number) => (screenWidth / 375) * value;
const responsiveHeight = (value: number) => (screenHeight / 812) * value;

// 使用示例

import React, { useState, useRef, useEffect } from 'react';
import {
    View,
    Text,
    TextInput,
    TouchableOpacity,
    StyleSheet,
    ScrollView,
    KeyboardAvoidingView,
    Platform,
    ActivityIndicator,
    Keyboard
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useResponsiveContext } from '../components/ResponsiveProvider';
import ResponsiveText from '../components/ResponsiveText';
import ResponsiveView from '../components/ResponsiveView';
import { wp, hp, sp } from '../utils/layout';
import { FONT_SIZES, fontSize } from '../utils/fontSize';
import { createResponsiveStyles } from '../utils/StyleUtils';
import DeviceInfo from '../utils/DeviceInfo';

// DeepSeek AI API集成
const fetchDeepSeekAnswer = async (question: string): Promise<string> => {
    try {
        console.log('发送请求到DeepSeek API...');

        // 使用完整URL而不是相对路径
        const apiUrl = 'https://api.siliconflow.cn/v1/chat/completions';
        console.log('API请求URL:', apiUrl);

        const response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer sk-soegwyizkxmihanelvxoxehfohlrxxmyveeffmcfplebomiu',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                model: 'deepseek-ai/DeepSeek-V3',
                messages: [
                    {
                        role: 'system',
                        content: '你是一位专业的医疗健康顾问，提供准确、专业的健康建议。'
                    },
                    {
                        role: 'user',
                        content: question
                    }
                ],
                stream: false,
                temperature: 0.7,
                max_tokens: 2000
            }),
        });

        console.log('收到API响应，状态码:', response.status);

        if (!response.ok) {
            const errorText = await response.text();
            console.log('API错误响应状态码:', response.status);
            console.log('API错误响应内容:', errorText);

            let errorMessage;
            try {
                const errorData = JSON.parse(errorText);
                errorMessage = errorData.message || errorData.error || '未知错误';
            } catch {
                errorMessage = errorText || response.statusText;
            }
            throw new Error(`请求失败 (${response.status}): ${errorMessage}`);
        }

        const responseText = await response.text();
        console.log('API原始响应:', responseText);

        let data;
        try {
            data = JSON.parse(responseText);
            console.log('API响应成功:', data);
        } catch (parseError) {
            console.log('解析API响应失败:', parseError);
            return `API返回的不是有效的JSON格式：${responseText.substring(0, 100)}...`;
        }

        // 检查响应数据结构
        if (data.choices && data.choices.length > 0 && data.choices[0].message) {
            return data.choices[0].message.content;
        } else {
            console.log('API响应格式异常:', data);
            return '获取AI回复失败，响应格式异常';
        }
    } catch (e: any) {
        console.log('AI接口异常:', e);

        // 错误提示信息
        return `由于API调用问题，暂时无法获取回复：${e.message}`;
    }
};

const Ceshi = () => {
    const navigation = useNavigation();
    const [input, setInput] = useState('');
    const [messages, setMessages] = useState([
        { text: '您好，我是您的AI健康顾问，有什么可以帮助您的吗？', sender: 'ai' }
    ]);
    const [loading, setLoading] = useState(false);
    const { orientation, isTablet } = useResponsiveContext();
    const scrollViewRef = useRef<ScrollView>(null);
    const [keyboardVisible, setKeyboardVisible] = useState(false);

    const tips = [
        '请分析我最近7天的健康数据',
        '嗓子疼，需要注意什么？',
    ];

    useEffect(() => {
        const keyboardDidShowListener = Keyboard.addListener(
            'keyboardDidShow',
            () => {
                setKeyboardVisible(true);
                scrollToBottom();
            }
        );
        const keyboardDidHideListener = Keyboard.addListener(
            'keyboardDidHide',
            () => {
                setKeyboardVisible(false);
            }
        );

        return () => {
            keyboardDidShowListener.remove();
            keyboardDidHideListener.remove();
        };
    }, []);

    useEffect(() => {
        scrollToBottom();
    }, [messages]);

    const scrollToBottom = () => {
        setTimeout(() => {
            scrollViewRef.current?.scrollToEnd({ animated: true });
        }, 100);
    };

    const handleSend = async () => {
        if (!input.trim()) return;

        const newMessages = [...messages, { text: input, sender: 'user' }];
        setMessages(newMessages);
        setInput('');
        setLoading(true);

        try {
            const aiReply = await fetchDeepSeekAnswer(input);
            setMessages([
                ...newMessages,
                { text: aiReply, sender: 'ai' }
            ]);
        } catch (e) {
            setMessages([
                ...newMessages,
                { text: 'AI服务暂时不可用，请稍后再试。', sender: 'ai' }
            ]);
        }

        setLoading(false);
    };

    const handleTip = (tip: string) => {
        setInput(tip);
    };

    return (
        <ResponsiveView style={styles.container}>
            {/* 添加头部导航栏 */}
            <ResponsiveView style={styles.header}>
                <TouchableOpacity
                    style={styles.backButton}
                    onPress={() => navigation.goBack()}
                >
                    <Icon name="arrow-back" size={24} color="#333" />
                </TouchableOpacity>
                <ResponsiveText style={styles.headerTitle}>问一问</ResponsiveText>
                <View style={styles.headerRight} />
            </ResponsiveView>

            {/* 开发模式下显示设备信息 */}
            {/*__DEV__ && <DeviceInfo />*/}

            {/* 顶部通知栏 */}
            <ResponsiveView style={styles.topNotice}>
                <ResponsiveText style={styles.topNoticeText} numberOfLines={1} onPress={() => navigation.navigate('Health')}>
                    您的血压指标近期有波动，建议及时进行复查并关注健康。
                </ResponsiveText>
                <Icon name="chevron-right" size={16} color="#FF9500" />
            </ResponsiveView>

            <KeyboardAvoidingView
                behavior={Platform.OS === 'ios' ? 'padding' : undefined}
                style={{ flex: 1 }}
                keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
            >
                <ScrollView
                    style={styles.messageArea}
                    ref={scrollViewRef}
                    contentContainerStyle={styles.messageContentContainer}
                >
                    {/* 每日药物小常识 */}
                    <ResponsiveView style={styles.dailyTipCard}>
                        <ResponsiveView style={styles.dailyTipHeader}>
                            <Icon name="lightbulb" size={18} color="#FFB700" />
                            <ResponsiveText style={styles.dailyTipTitle}>
                                每日药物小常识
                            </ResponsiveText>
                        </ResponsiveView>
                        <ResponsiveText style={styles.dailyTipSubtitle}>
                            阿司匹林服用小贴士：正确服用方法及注意...
                        </ResponsiveText>
                        <ResponsiveText style={styles.dailyTipContent}>
                            阿司匹林是一种常见的解热镇痛药，但它的使用方法和注意事项却经常被人们忽视。
                        </ResponsiveText>
                    </ResponsiveView>

                    {/* 聊天内容 */}
                    {messages.map((msg, idx) => (
                        <ResponsiveView
                            key={idx}
                            style={msg.sender === 'user' ? styles.userMsg : styles.aiMsg}
                        >
                            <ResponsiveText style={msg.sender === 'user' ? styles.userText : styles.aiText}>
                                {msg.text}
                            </ResponsiveText>
                        </ResponsiveView>
                    ))}

                    {loading && (
                        <ResponsiveView style={styles.aiMsg}>
                            <ActivityIndicator size="small" color="#007AFF" style={{ marginRight: 5 }} />
                            <ResponsiveText style={styles.aiText}>
                                AI正在思考...
                            </ResponsiveText>
                        </ResponsiveView>
                    )}

                    {/* 推荐提问 */}
                    <ResponsiveView style={styles.tipsArea}>
                        <ResponsiveText style={styles.tipsTitle}>
                            你可以这样问
                        </ResponsiveText>
                        {tips.map((tip, idx) => (
                            <TouchableOpacity
                                key={idx}
                                style={styles.tipItem}
                                onPress={() => handleTip(tip)}
                            >
                                <ResponsiveText style={styles.tipText}>
                                    {tip}
                                </ResponsiveText>
                            </TouchableOpacity>
                        ))}
                    </ResponsiveView>
                </ScrollView>

                {/* 底部功能按钮 */}
                <ResponsiveView style={styles.functionBar}>
                    <TouchableOpacity style={styles.functionBtn}>
                        <ResponsiveText style={styles.functionBtnText}>
                            症状分析
                        </ResponsiveText>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.functionBtn}>
                        <ResponsiveText style={styles.functionBtnText}>
                            病历分析
                        </ResponsiveText>
                    </TouchableOpacity>
                </ResponsiveView>

                {/* 输入框和发送按钮 */}
                <ResponsiveView style={styles.inputBar}>
                    <TouchableOpacity style={styles.addButton}>
                        <Icon name="add" size={22} color="#007AFF" />
                    </TouchableOpacity>
                    <TextInput
                        style={styles.input}
                        value={input}
                        onChangeText={setInput}
                        placeholder="有什么健康问题吗？"
                        placeholderTextColor="#999"
                        editable={!loading}
                    />
                    <TouchableOpacity
                        style={styles.sendButton}
                        onPress={handleSend}
                        disabled={loading || !input.trim()}
                    >
                        <Icon
                            name="send"
                            size={22}
                            color={input.trim() ? "#007AFF" : "#ccc"}
                        />
                    </TouchableOpacity>
                </ResponsiveView>
            </KeyboardAvoidingView>
        </ResponsiveView>
    );
};

const styles = createResponsiveStyles({
    container: {
        flex: 1,
        backgroundColor: '#F8F9FB',
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: wp(16),
        paddingVertical: hp(12),
        backgroundColor: '#fff',
        borderBottomWidth: StyleSheet.hairlineWidth,
        borderBottomColor: '#E0E0E0',
    },
    backButton: {
        padding: wp(4),
    },
    headerTitle: {
        fontSize: sp(17),
        fontWeight: 'bold',
        color: '#333',
        textAlign: 'center',
        flex: 1,
        marginHorizontal: wp(16),
    },
    headerRight: {
        width: wp(24),
    },
    topNotice: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#FFF7E6',
        paddingHorizontal: wp(12),
        paddingVertical: hp(8),
        borderBottomWidth: 1,
        borderBottomColor: '#FFE0B2',
    },
    topNoticeText: {
        color: 'rgba(255,125,0,1)',
        flex: 1,
        fontSize: sp(13),
    },
    messageArea: {
        flex: 1,
        paddingHorizontal: wp(12),
        paddingTop: hp(10),
    },
    messageContentContainer: {
        paddingBottom: hp(20),
    },
    dailyTipCard: {
        backgroundColor: '#FFFFFF',
        borderRadius: 8,
        padding: wp(12),
        marginBottom: hp(10),
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.1,
        shadowRadius: 2,
        elevation: 1,
        borderWidth: 1,
        borderColor: '#E6F0FF',
    },
    dailyTipHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: hp(6),
    },
    dailyTipTitle: {
        fontWeight: 'bold',
        color: 'rgba(210,95,0,1)',
        marginLeft: wp(6),
        fontSize: sp(15),
    },
    dailyTipSubtitle: {
        marginTop: hp(15),
        fontWeight: 'bold',
        color: '#333',
        fontSize: sp(14),
        marginBottom: hp(8),
    },
    dailyTipContent: {
        color: '#666',
        lineHeight: hp(18),
        fontSize: sp(13),
    },
    userMsg: {
        alignSelf: 'flex-end',
        backgroundColor: '#DCF8C6',
        borderRadius: 12,
        borderBottomRightRadius: 4,
        paddingHorizontal: wp(12),
        paddingVertical: hp(8),
        marginBottom: hp(8),
        maxWidth: wp(280),
        width: 'auto',
    },
    userText: {
        color: '#000',
        fontSize: sp(14),
    },
    aiMsg: {
        alignSelf: 'flex-start',
        backgroundColor: '#FFFFFF',
        borderRadius: 12,
        borderBottomLeftRadius: 4,
        paddingHorizontal: wp(12),
        paddingVertical: hp(8),
        marginBottom: hp(8),
        maxWidth: wp(280),
        width: 'auto',
        flexDirection: 'row',
        alignItems: 'center',
    },
    aiText: {
        color: '#333',
        fontSize: sp(14),
    },
    tipsArea: {
        marginTop: hp(12),
        marginBottom: hp(12),
    },
    tipsTitle: {
        color: "rgba(29, 33, 41, 1)",
        fontFamily: " PingFangSC-regular",
        marginBottom: hp(8),
        fontSize: sp(14),
    },
    tipItem: {
        backgroundColor: '#EFEFEF',
        borderRadius: 16,
        paddingHorizontal: wp(12),
        paddingVertical: hp(6),
        marginBottom: hp(6),
        alignSelf: 'flex-start',
        marginTop: hp(15),
    },
    tipText: {
        color: '#333',
        fontSize: sp(13),
    },
    functionBar: {
        flexDirection: 'row',
       
        paddingVertical: hp(8),
        backgroundColor: '#f5f7fa',
        borderTopWidth: StyleSheet.hairlineWidth,
        borderTopColor: '#E0E0E0',
        marginLeft: wp(20),
        border: 0,
        position: 'relative',
        zIndex: 1
    },
    functionBtn: {
        backgroundColor: '#f0f6ff',
        borderRadius: 20,
        paddingHorizontal: wp(20),
        paddingVertical: hp(8),
        minWidth: wp(120),
        alignItems: 'center',
        borderWidth: 1,
        borderColor: '#d6e4ff',
        marginLeft: wp(10),
    },
    functionBtnText: {
        color: '#3069e3',
        fontWeight: 'bold',
        fontSize: sp(14),
    },
    inputBar: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: wp(10),
        paddingVertical: hp(8),
        backgroundColor: '#FFF',
        borderTopWidth: StyleSheet.hairlineWidth,
        borderTopColor: '#E0E0E0',
        position: 'relative',
        zIndex: 1,
        paddingBottom: Platform.OS === 'ios' ? hp(10) : hp(8)
    },
    addButton: {
        marginRight: wp(8),
        padding: wp(4)
    },
    input: {
        flex: 1,
        height: hp(37),
        backgroundColor: '#F2F4F7',
        borderRadius: 18,
        paddingHorizontal: wp(12),
        marginRight: wp(8),
        fontSize: sp(14),
    },
    sendButton: {
        padding: wp(4),
    },
});

export default Ceshi;


